#!/usr/bin/env python
# coding:utf-8
from PoboAPI import *
import datetime
import numpy as np
from copy import *
import math



#开始时间，用于初始化一些参数
#视频可见 video at https://www.bilibili.com/video/av69461082/?p=7
def OnStart(context) :
    print( "I\'m starting...")
    #登录交易账号，需在主页用户管理中设置账号，并把期货测试替换成您的账户名称
    context.myacc = None


    context.MyAlarm1 = SetAlarm(datetime.time(9, 30))
    context.MyAlarm2 = SetAlarm(datetime.time(9, 40))
    context.MyAlarm3 = SetAlarm(datetime.time(14, 50))

    if "回测期货" in context.accounts:
        print ("登录交易账号[回测期货]")
        if context.accounts["回测期货"].Login() :
            context.myacc = context.accounts["回测期货"]
            

def OnMarketQuotationInitialEx(context, exchange,daynight):
    if exchange != 'DCE':
        return

    g.biaodi = GetMainContract('DCE', 'm',20)

    g.code = GetAtmOptionContractByPos(g.biaodi,"now",-1,0, None)


#实时行情事件，当有新行情出现时调用该事件Ex
def OnAlarm(context, alarmid) :
    
    

    dyndata = GetQuote(g.code)
    if dyndata:
        n  = context.myacc.GetValidVolume(g.code,BSType.SellOpen,dyndata.now)
#         print('可开数量' + str(n))
        
        OpenMargin = CalcOpenMargin(context.myacc,g.code,volume = 1,direction='sell',price=dyndata.now)
#         print('开仓保证金' + str(OpenMargin))
        
#         #费率
#         margin_value = context.myacc.GetMargin(g.code,BSType.SellOpen)
#         print (margin_value.Rate)
#         print (margin_value.Unit)
        
#         value = PBObj()
# #         value.Rate = 0.2
#         value.Unit = 3000
#         context.myacc.SetMargin(g.code,value,BSType.SellOpen) 
    
#         context.myacc.RefreshMargin(g.code,BSType.SellOpen) 
        
        
#         fee_value = context.myacc.GetFee(g.code)
#         print(fee_value.OpenUnit)

        
#         fee = PBObj()
#         fee.OpenUnit = 3
#         fee.CloseRate = 0.004
#         fee.CloseTodayRate = 0.005
#         fee.MiniFee = 3
#         context.myacc.SetFee(g.code,fee)
        
#         context.myacc.RefreshFee(g.code) 
#         print ('费率结束========================')
        
    price = PriceType(PbPriceType.Limit,limit_price_type=16)
    
    if alarmid == context.MyAlarm2:
        print( '开仓')
        QuickInsertOrder(context.myacc,g.code,'sell','open',price,math.floor(n/2))
        QuickInsertOrder(context.myacc,g.code,'sell','open',price,100)
#         QuickInsertSmartReorder(context.myacc,g.code, BSType.SellOpen,PriceType(PbPriceType.Limit,16,0),10, PriceType(PbPriceType.Limit,16,0),3,max_price_offset = 20,time_out= 3000)
#         QuickInsertSmartSplitOrder(context.myacc,g.code, BSType.SellOpen, PriceType(PbPriceType.Limit,16,0), math.floor(n/2),10, volume1 = 2, volume2 = 8)
 
        
    elif alarmid == context.MyAlarm3:
        option1 = PBObj()
        option1.contract = g.code
        positions = context.myacc.GetPositions(option1)
#         print(positions)
        
#         posiDetails = context.myacc.GetPosiDetails()
#         print(posiDetails)
#         for posd in posiDetails:
#             print(posd.volume)

#         bal = context.myacc.AccountBalance
#         print('动态权益' + str(bal.DynamicNetAssets))

#         ods = context.myacc.GetTradeDetails()
#         print (ods)
#         for i in ods:
#             logorder(context,i)
            
        orders = context.myacc.GetOrders()
        print(orders)
        for order in orders:
            print ('委托编号' + str(order.id))

# def OnOrderChange(context, AccountName, order) :
#     print(order.IsCanCancel())
# #     撤单
#     if order.IsCanCancel() == True:
#         context.myacc.CancelOrder(order)            
            


        
def logorder(context,a):
    if a ==None:
        return
    print ('成交信息++++++++++++++++++++')
    print( '交易账号' + a.accountname)
    print( '成交编号' + str(a.id))
    print( '委托编号' + str(a.orderid))
    print ('交易合约' + a.contract)
    print( '成交数量' + str(a.volume) )
    print( '成交价格' + str(a.price) )
    print( '成交时间' + str(a.TradeTime) )
    print( '买卖方向' + str(a.bstype.BuySellFlag) )
    print( '开平方向' + str(a.bstype.OffsetFlag) )

    
    

